# -*- coding: utf-8 -*-
"""
Created on Fri Apr 29 11:53:08 2022

@author: dell

计算效应子和最近重复序列的距离，并标记重复序列类型
输出：效应子id+重复序列类型+最小距离
"""

import sys
import pandas as pd

repeat_file = r"C:\Users\dell\Desktop\repeatmasker.txt"
#rxlr_file = r"C:\Users\dell\Desktop\rxlr.txt"
rxlr_file = r"C:\Users\dell\Desktop\random_genes.txt" # gene_file

dis_set = []
repeat_set = []
rxlr_set = []


result = []
# repeat_pd = pd.read_table(repeat_file, sep="\t", header=None)
# print(repeat_pd.head(10))
#def 
with open(rxlr_file, 'r') as f1:
    for i in f1.readlines():
        rxlr_contig = i.split("\t")[1]
        rxlr_id = i.split("\t")[0]
        rxlr_coord = i.split("\t")[2]
#        print(i.strip())
        with open(repeat_file, 'r') as f2:
            for j in f2.readlines():
                repeat_contig = j.split("\t")[0]
                repeat_id = j.split("\t")[3]
                repeat_coord = j.split("\t")[4]
#                print(j.strip())                
                if rxlr_contig == repeat_contig:
                    #print(repeat_contig)
                    distance = abs(int(rxlr_coord) - int(repeat_coord))                    
                    dis_set.append(distance)
                    repeat_set.append(repeat_id)
                    rxlr_set.append(rxlr_id)
    
#print(rxlr_set)

# pd_ = pd.read_csv(dis_set)
merge = {"rxlr_id": rxlr_set, "distance": dis_set, "repeat_name": repeat_set}
df = pd.DataFrame(merge)
#print(df.head(10))
result = df.groupby("rxlr_id")["distance"].min()
result2 = df.groupby('rxlr_id').apply(lambda t: t[t.distance==t.distance.min()])
print(result)
result2.to_csv("random_genes_repeat_dis_simple.csv")

